<?php

namespace App\Http\Controllers\PersonInfoManagement;

use App\Http\Controllers\Controller;
use App\Models\Constant\Fields;
use App\Models\PersonInfoManagement\PersonInfo;
use App\Models\SystemManagement\Employee;
use App\Models\SystemManagement\Banci;
use App\Models\SystemManagement\Skill;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

/**
 * Class PersonInfoController
 * @package App\Http\Controllers\PersonInfoManagement
 * @group 人员信息管理
 */
class PersonInfoController extends Controller{

    /**
     * 人员信息管理列表 -- 关联关系查询
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam organization_id int required 组织id 外键 组织表
     * @bodyParam department_id int required 部门id 外键 部门表
     * @bodyParam post_id int required 岗位id 外键 岗位表
     * @bodyParam name string required 员工姓名
     *
     * @queryParam id ID
     * @queryParam skill->name 岗位等级
     * @queryParam name 姓名
     * @queryParam phone 手机号
     * @queryParam banci->name 班次
     * @queryParam workspace 作业区域 1组内作业 2临时作业
     *
     *
     */
    public function index(Request $request){
        $per_page = \request()->input('per_page');
        $data = Employee::orderBy('id','desc')
                ->where(function($query) use ($request){
                    $name = $request->input('name','');
                    $organization_id = $request->input('organization_id','');
                    $department_id = $request->input('department_id','');
                    $post_id = $request->input('post_id','');
                    if(!empty($name)){
                        $query->where('name','like','%'.$name.'%');
                    }
                    if(!empty($organization_id)) {
                        $query->where('organization_id',$organization_id);
                    }
                    if(!empty($department_id)) {
                        $query->where('department_id',$department_id);
                    }
                    if(!empty($post_id)) {
                        $query->where('post_id',$post_id);
                    }
                })
                ->select('id','name','skill_id','phone')
                ->with(['skill','personInfo'])
                ->paginate($per_page);
        if(count($data) == 0){
            return response()->json(encodeMsg("没有数据",404));
        }
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 人员信息管理 -- 员工排班
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam employee_id int required 员工id 外键 员工表
     * @bodyParam banci_id int required 班次id 外键 班次表
     * @bodyParam workspace int required 作业区域
     *
     * @queryParam employee_id int required 员工id 外键 员工表
     * @queryParam banci_id int required 班次id 外键 班次表
     * @queryParam workspace int required 作业区域 1组内作业 2临时作业
     *
     *
     */
    public function store(Request $request){
        try{
            $info = PersonInfo::create($request->all());
            return response()->json(encodeMsg($info,200));
        } catch (QueryException $e) {
            // dd($e);
            return response()->json(encodeMsg(['message' => '数据添加失败!'],400));
        }
    }

    /**
     * 查看人员排班信息
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id int required 人员信息ID
     *
     * @queryParam skill->name 岗位等级
     * @queryParam name 姓名
     * @queryParam phone 手机号
     * @queryParam banci->name 班次
     * @queryParam workspace 作业区域 1组内作业 2临时作业
     *
     *
     */
    public function show($id){
        if(is_null(Employee::find($id))){
            return response()->json(encodeMsg("此记录不存在",404));
        }
        $person_info = Employee::where(Fields::ID,$id)
                        ->with(['skill','personInfo'])
                        ->get(['id','name','skill_id','phone']);
        return response()->json(encodeMsg($person_info,200));
    }

    /**
     * 修改人员排班信息
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id int required 员工id 外键 员工
     * @bodyParam banci_id int required 班次 外键 班次
     * @bodyParam workspace int required 作业区域 1组内作业 2临时作业
     *
     * @response 205 {"code":205,"msg":"Updated","data":"\u4fee\u6539\u6210\u529f"}
     * @response 400 {"code": 400,"msg": "param error","data": "参数错误"}
     * @response 404 {"code":404,"msg":"Not Found","data":"\u6ca1\u6709\u8be5\u8bb0\u5f55"}
     */
    public function update(\App\Http\Requests\PersonInfo\PersonInfo $request,$id){
        $employee = Employee::find($id);
        if(is_null($employee)){
            return response()->json(encodeMsg("此记录不存在",404));
        }
        try{
            $data = $request->only(['banci_id','workspace']);
            PersonInfo::where('employee_id',$id)->update($data);
            return response()->json(encodeMsg($data,200));
        } catch (QueryException $e) {
            dd($e);
            return response()->json(encodeMsg(['message' => '数据修改失败!'],400));
        }
    }

    /**
     * 人员信息导出 excel
     * @queryParam id 序号
     * @queryParam skill->name 岗位等级
     * @queryParam name 姓名
     * @queryParam phone 手机号
     * @queryParam person_info->banci->name 班次
     * @queryParam person_info->workspace|status:1=>组内作业,2=>临时作业 作业区域
     *
     */
    public function export(Request $request)
    {
        $request['per_page'] = 9999;
        $cellData = $this->index($request);//excel的内容
        $data = $cellData->getData()->data->data;
        $writer = excelExport($data,genExport());
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="人员信息.xlsx"');//execl名字
        $writer->save('php://output');
    }

    /**
     * 人员信息导入 excel
     * @queryParam id 序号
     * @queryParam skill->name 岗位等级
     * @queryParam name 姓名
     * @queryParam phone 手机号
     * @queryParam person_info->banci->name 班次
     * @queryParam person_info->workspace|status:1=>组内作业,2=>临时作业 作业区域
     *
     */
    public function import(Request $request)
    {
        $data = excelImport($request);
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                unset($v[0]);
                foreach ($v as $key=>$row) {
                    //逻辑处理
                    $employee[$k][$key]['name'] = $row[1];
                    $employee[$k][$key]['phone'] = $row[2];
                    $skill = $row[3];
                    DB::beginTransaction();
                    try {
                        //判断岗位等级是否存在，没有则新增
                        $id = Skill::where('name',$skill)->first('id');
                        if (!empty($id)) {
                            $employee[$k][$key]['skill_id'] = $id->id;
                        } else if(!empty($skill)) {
                            $info = Skill::create($skill);
                            $employee[$k][$key]['skill_id'] = $info->id;
                        }
                        //判断员工是否存在，没有则新增
                        $employee_id = Employee::where($employee[$k][$key])->first('id');
                        if (!empty($employee_id)) {
                            $info[$k][$key]['employee_id'] = $employee_id->id;
                        } else {
                            $info = Employee::addData($employee[$k][$key]);
                            $info[$k][$key]['employee_id'] = $info->id;
                        }
                        //判断班次是否存在，没有则新增
                        $banci = $row[4];
                        $banci_id = Banci::where('name',$banci)->first('id');
                        if (!empty($banci_id)) {
                            $info[$k][$key]['banci_id'] = $banci_id->id;
                        } else if(!empty($banci)){
                            $info = Banci::create($banci);
                            $info[$k][$key]['banci_id'] = $info->id;
                        }
                        //判断作业区域类型
                        if($row[5] == '组内作业') {
                            $info[$k][$key]['workspace'] = 1;
                        } else if($row[5] == '临时作业') {
                            $info[$k][$key]['workspace'] = 2;
                        } else if(!empty($row[5])) {
                            $info[$k][$key]['workspace'] = 3;
                        }
                        //根据是否存在班次信息确定是否新增人员信息中间表
                        if(!empty($info[$k][$key]['banci_id'])) {
                            $res = PersonInfo::where($info[$k][$key])->first();
                            if (empty($res)) {
                                PersonInfo::create($info[$k][$key]);
                            }
                        }
                        DB::commit();
                    } catch (QueryException $e) {
                        DB::rollBack();
                        // dd($e);
                        return response()->json(encodeMsg(['message' => '导入失败!'],400));
                    }
                    unset($employee[$k][$key]);
                    unset($info[$k][$key]);
                }
                unset($employee[$k]);
                unset($info[$k]);
            }
            if(Storage::disk('public')->exists('uploads/'.$request->file('file')->getClientOriginalName())) {
                 return response()->json(encodeMsg(['message' => '文件已上传!'],200));
            }
        }
    }

}
